package ext.mango.aa.po;

import java.util.ArrayList;
import java.util.List;

import ext.mango.aa.eo.EOAAMenu;
import ext.mango.base.POBase;
import ext.mango.functions.Func;
import mango.functions.FuncString;
import mango.orm.DaoFactory;
import mango.orm.entity.Entity;
import mango.web.Info;

public class Index extends POBase {
    private List<String> inGroupMenuIds = new ArrayList<String>();
    private String groupId = null;

    public boolean menu() {
        this.groupId = this.getRequestParameter("GROUPID");
        if(this.isGroupMenu() && !"Super".equals(this.groupId)){
            String sql = "select menuid from AAMenuToUserGroup where UserGroupId=@groupid";
            this.inGroupMenuIds = DaoFactory.c(sql).setParamByName("groupid", this.groupId).listQueryString();
        }
    	this.setResult(this.getMenu());
    	return true;
    }

    private String getSQLCondition() {
        String sql = "";
        if (!this.isSuperUser()) {
            sql += " and id in(" + "SELECT MenuId FROM AAMenuToUserGroup WHERE UserGroupId IN("
            + "SELECT usergroupid FROM AAUserToUserGroup WHERE userId=@userid" + ")"
            + ")";
        }
        sql += " order by menuorder";
        return sql;
    }

    private List<Entity> getParentMenus() {
        String sql = "select * from AAMenu where parent='-1'" + this.getSQLCondition();
        List<Entity> menuList = DaoFactory.c(sql, EOAAMenu.class)
                .setParamByName("userid", this.getCurrentUser().getId())
                .setParamByName("groupid", this.groupId).listQuery();
        return menuList;
    }

    private List<Entity> getSubMenus(String parentId) {
        String sql = "select * from AAMenu where parent=@parent " + this.getSQLCondition();
        List<Entity> menuList = DaoFactory.c(sql, EOAAMenu.class)
                .setParamByName("userid", this.getCurrentUser().getId())
                .setParamByName("groupid", this.groupId).setParamByName("parent", parentId).listQuery();
        return menuList;
    }

    public String getMenu() {
        List<Entity> menuList = this.getParentMenus();
        StringBuilder ret = new StringBuilder();
        ret.append("{text:'.', id:'root',children:[");
        for (Entity menu : menuList) {
            EOAAMenu root = (EOAAMenu) menu;
            ret.append(menu2JSON(root, "/root")).append(",");
        }
        if (menuList.size() > 0) {
            ret.delete(ret.length() - 1, ret.length());
        }
        ret.append("]}");
        return ret.toString();
    }

    private boolean isGroupMenu() {
        if (FuncString.isBlank(this.groupId)) {
            return false;
        }
        return true;
    }

    public String menu2JSON(EOAAMenu menu, String path) {
        StringBuilder ret = new StringBuilder();
        path = path + "/" + menu.getId();
        ret.append("{text:'").append(menu.getTitle()).append("',link:'").append(menu.getLink())
                .append("',order:'").append(menu.getMenuOrder()).append("',id:'")
                .append(menu.getId()).append("', path:'").append(path).append("',");
        if (!FuncString.isBlank(menu.getIconCls()) && this.hasIcon()) {
            ret.append("iconCls:'").append(menu.getIconCls()).append("',");
        }
        if(this.isGroupMenu()){
            ret.append("expanded:true,");
        }
        if ("1".equals(menu.getLeaf())) {
            if (this.isGroupMenu()){
                if("Super".equals(this.groupId)){
                    ret.append("checked:true,");
                }
                else {
                    if(this.inGroupMenuIds.contains(menu.getId())){
                        ret.append("checked:true,");
                    }
                    else {
                        ret.append("checked:false,");
                    }
                }
            }
            ret.append("leaf:true");
        }
        else {
            ret.append("children:[");
            List<Entity> children = this.getSubMenus(menu.getId());
            for (Entity entity : children) {
                EOAAMenu child = (EOAAMenu) entity;
                ret.append(menu2JSON(child, path)).append(",");
            }
            if (children.size() > 0) {
                ret.delete(ret.length() - 1, ret.length());
            }
            ret.append("]");
        }
        ret.append("}");
        return ret.toString();
    }
    
    private boolean hasIcon() {
        if ("Neptune".equals(this.getCurrentUser().getTheme())) {
            return false;
        }
        return true;
    }
    
    public boolean changeTheme(){
        String theme = this.getRequestParameter("THEME");
        String sql = "update AAUser set theme=? where id=?";
        DaoFactory.c(sql).setParameter(theme, this.getCurrentUser().getId()).executeUpdate();
        this.getCurrentUser().setTheme(theme);
        this.setSessionAttr("theme", Func.getThemeStyle(this.getCurrentUser()));
        this.addInfo(Info.SUCCESS, "OK");
        return true;
    }
}
